import 'dart:convert';
import 'package:injectable/injectable.dart';
import 'package:vista/shared/models/daily_inspiration.dart';
import 'package:vista/shared/models/photo_params.dart';
import 'package:vista/shared/services/storage_service.dart';
import 'package:vista/shared/services/auth_focus.dart';

/// 每日灵感服务
/// 处理每日灵感的管理，如摄影中的灵感收集般组织内容
@lazySingleton
class DailyInspirationService {
  final StorageService _storageService;
  final AuthFocus _authFocus;
  static const String _inspirationsKey = 'daily_inspirations';
  static const String _isInitializedKey = 'daily_inspirations_initialized';

  DailyInspirationService(this._storageService, this._authFocus);

  /// 初始化默认每日灵感数据
  /// 创建3条默认灵感数据
  Future<void> initializeDefaultInspirations() async {
    final isInitialized = await _storageService.retrieveBool(_isInitializedKey);
    if (isInitialized == true) {
      return; // 已经初始化过了
    }

    final users = await _authFocus.getUsers();
    if (users.isEmpty) {
      return;
    }

    final now = DateTime.now();
    final defaultInspirations = <DailyInspiration>[];

    // 创建3条默认灵感数据
    final authors = users.take(3).toList();
    final titles = ['Golden Hour Magic', 'Urban Landscape', 'Nature\'s Beauty'];
    final descriptions = [
      'Capturing the warm, golden light of sunset creates a magical atmosphere that transforms ordinary scenes into extraordinary moments.',
      'The contrast between modern architecture and natural elements creates a dynamic composition that tells a story of urban life.',
      'Nature provides endless inspiration with its intricate details, vibrant colors, and ever-changing landscapes that never fail to amaze.',
    ];
    final images = [
      'assets/images/inspiration_3.png',
      'assets/images/inspiration_2.png',
      'assets/images/inspiration_1.png',
    ];

    for (int i = 0; i < 3 && i < authors.length; i++) {
      final author = authors[i];
      final inspirationId = 'inspiration_${now.millisecondsSinceEpoch}_$i';

      defaultInspirations.add(
        DailyInspiration(
          id: inspirationId,
          authorId: author.id,
          title: titles[i],
          description: descriptions[i],
          image: images[i],
          photoParams: _getPhotoParams(i),
          timestamp: now.subtract(Duration(days: 2 - i, hours: i * 4)),
        ),
      );
    }

    // 保存所有数据
    await _saveInspirations(defaultInspirations);
    await _storageService.persistBool(_isInitializedKey, true);
  }

  /// 获取摄影参数
  PhotoParams _getPhotoParams(int index) {
    final paramsList = [
      PhotoParams(
        lens: '22.4 mm f/2.8',
        fl: '8',
        flash: 'off',
        exposure: 'Manual',
        camera: 'DJI FC3411',
        iso: '100',
        shutter: '1/100s',
        aperture: 'f/2.8',
      ),
      PhotoParams(
        lens: '50 mm f/1.8',
        fl: '50',
        flash: 'off',
        exposure: 'Aperture Priority',
        camera: 'Canon EOS R5',
        iso: '200',
        shutter: '1/250s',
        aperture: 'f/1.8',
      ),
      PhotoParams(
        lens: '24-70 mm f/2.8',
        fl: '35',
        flash: 'on',
        exposure: 'Shutter Priority',
        camera: 'Nikon D850',
        iso: '400',
        shutter: '1/60s',
        aperture: 'f/2.8',
      ),
    ];
    return paramsList[index % paramsList.length];
  }

  /// 保存灵感列表
  Future<void> _saveInspirations(List<DailyInspiration> inspirations) async {
    final inspirationsJson = inspirations.map((i) => i.toJson()).toList();
    final inspirationsString = jsonEncode(inspirationsJson);
    await _storageService.persistString(_inspirationsKey, inspirationsString);
  }

  /// 获取所有每日灵感
  Future<List<DailyInspiration>> getAllInspirations() async {
    final inspirationsString = await _storageService.retrieveString(
      _inspirationsKey,
    );
    if (inspirationsString == null) {
      return [];
    }

    try {
      final List<dynamic> inspirationsJson = jsonDecode(inspirationsString);
      return inspirationsJson
          .map(
            (json) => DailyInspiration.fromJson(json as Map<String, dynamic>),
          )
          .toList()
        ..sort((a, b) => b.timestamp.compareTo(a.timestamp));
    } catch (e) {
      return [];
    }
  }

  /// 根据ID获取每日灵感
  Future<DailyInspiration?> getInspirationById(String inspirationId) async {
    final inspirations = await getAllInspirations();
    try {
      return inspirations.firstWhere((i) => i.id == inspirationId);
    } catch (e) {
      return null;
    }
  }

  /// 根据用户ID获取每日灵感
  Future<List<DailyInspiration>> getInspirationsByUser(String userId) async {
    final inspirations = await getAllInspirations();
    return inspirations.where((i) => i.authorId == userId).toList()
      ..sort((a, b) => b.timestamp.compareTo(a.timestamp));
  }
}
